# Multi-stage build for YOLOv8 OpenVINO Go Service

# Stage 1: Build C++ component
FROM ubuntu:22.04 as cpp-builder

RUN apt-get update && apt-get install -y \
    build-essential \
    cmake \
    git \
    libopencv-dev \
    pkg-config \
    && rm -rf /var/lib/apt/lists/*

# Install OpenVINO Runtime
RUN apt-get update && apt-get install -y \
    openvino-runtime \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /build

COPY YOLOv8-OpenVINO-CPP-Inference /build

RUN mkdir -p build && \
    cd build && \
    cmake .. -DCMAKE_BUILD_TYPE=Release && \
    make -j$(nproc)

# Stage 2: Build Go component
FROM golang:1.21-alpine as go-builder

RUN apk add --no-cache git

WORKDIR /build

COPY goyolo /build

RUN go mod download && \
    CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
    -o goyolo-service \
    -ldflags="-s -w" \
    .

# Stage 3: Runtime image
FROM ubuntu:22.04

RUN apt-get update && apt-get install -y \
    libopencv-core4.5d \
    libopencv-imgproc4.5d \
    libopencv-highgui4.5d \
    libopencv-imgcodecs4.5d \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# Install OpenVINO Runtime
RUN apt-get update && apt-get install -y \
    openvino-runtime \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy C++ binaries
COPY --from=cpp-builder /build/build/detect_service /app/bin/
COPY --from=cpp-builder /build/build/detect /app/bin/

# Copy Go binary
COPY --from=go-builder /build/goyolo-service /app/bin/

# Create necessary directories
RUN mkdir -p /app/models /tmp/yolov8_inference /tmp/yolov8_uploads

# Set permissions
RUN chmod +x /app/bin/*

# Expose port
EXPOSE 8080

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8080/health || exit 1

# Environment variables
ENV PORT=8080 \
    CONFIDENCE_THRESHOLD=0.5 \
    NMS_THRESHOLD=0.5 \
    INPUT_SIZE=640 \
    GIN_MODE=release

# Run the service
CMD ["/app/bin/goyolo-service"]

